#!/usr/bin/env python
# -*- coding: UTF-8 -*-
# @Project:     server
# @File:        login_api.py
# @Author:      Fan GuiChuan
# @Date:        2025/9/2 14:30
# @Version:     Python3.7
# @Description:
from datetime import datetime, timedelta

from flask import request

from app.utils.response import success_response, error_response
from app.services.user_serv import UserServ
from app.routes.auth import gen_token

user_map = {
    'admin': 'admin123'
}


class LoginApi:
    def __init__(self, logger, blueprint):
        self.logger = logger
        self.user_serv = UserServ(self.logger)
        self.blueprint = blueprint
        self.register_blueprint()

    def register_blueprint(self):
        self.blueprint.add_url_rule('/register', view_func=self.registered_user, methods=['POST'])
        self.blueprint.add_url_rule('/login_by_username', view_func=self.login_by_username, methods=['POST'])
        self.blueprint.add_url_rule('/refresh_token', view_func=self.refresh_token, methods=['POST'])

    def refresh_token(self):
        token = gen_token()
        expires_date = datetime.now() + timedelta(days=1)
        return {
            'success': True,
            'data': {
                'accessToken': token,
                'refreshToken': token,
                'expires': expires_date.strftime('%Y/%m/%d 00:00:00')
            }
        }

    def login_by_username(self):
        try:
            ret, data = self.user_serv.login_by_username()
            if ret:
                return {
                    'success': True,
                    'data': data
                }
            else:
                return error_response(data)
        except Exception as e:
            self.logger.exception(str(e))
            return error_response(str(e))

    def registered_user(self):
        try:
            self.logger.debug(f"registered user data: {request.json}")
            ret, data = self.user_serv.registered_user()
            if ret:
                return {
                    'success': True,
                    'data': data
                }
            else:
                return error_response(data)
        except Exception as e:
          self.logger.exception(str(e))
          return error_response(str(e))
